﻿#include "DataPackage.h"
#include "OutPutMessage.h"

#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>

#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlField>

DataPackage::DataPackage(QObject *parent)
	: QObject(parent)
{

}

DataPackage::~DataPackage()
{

}

/***********************************************************************************************************************************/
QString DataPackage::getError()
{
	return strError;
}

/***********************************************************************************************************************************/
void DataPackage::response(const QString & strMsg, bool bError, QJsonObject & reslut)
{
	strError.clear();

	if (bError)
	{
		strError = strMsg;
		reslut.insert("Error", strMsg);
	}
	else
	{
		reslut.insert("Success", strMsg);
	}

}

bool DataPackage::response(QSqlQuery & query, QJsonObject & records)
{
	strError.clear();

	/************************************************************************/
	//Table Data
	QJsonArray arrFileds;
    const QSqlRecord & fields = query.record();
	int count = fields.count();
	if (count > 0)
	{
		//table name
		records.insert("table", "");

		//Header
		for (int col = 0; col < count; ++col)
		{
            const QSqlField & field = fields.field(col);
			QJsonObject colObj;
			colObj.insert("name", field.name());
            colObj.insert("type", int(field.type()));
			colObj.insert("len", field.length());
			arrFileds.append(colObj);
		}
		records.insert("fields", arrFileds);

		//Row Datas
		QJsonArray arrDatas;
		while (query.next())
		{
			QJsonArray arrData;
			for (int i = 0; i < count; i++)
			{
				arrData.append(toJsonValue(query.value(i)));
			}

			arrDatas.append(arrData);
		}
		records.insert("records", arrDatas);
	}
	else
	{
		strError = tr("Table is null or select failed!");
		records.insert("Error", strError);
		return false;
	}

	if (records.isEmpty())
	{
		outPutMessage(strError, MSG_ERROR);
		strError = tr("data is null, to json failed!");
		records.insert("Error", strError);
		return false;
	}
	return true;
}

/***********************************************************************************************************************************/
QJsonValue DataPackage::toJsonValue(const QVariant & value)
{
	QVariant::Type type = value.type();
	switch (type)
	{
	case QVariant::Bool:
		return QJsonValue(value.toBool());
	case QVariant::Int:
		return QJsonValue(value.toInt());
	case QVariant::String:
		return QJsonValue(value.toString());

	default:
		return QJsonValue(value.toString());
	}
}
